import React, { useEffect, useState, Fragment } from 'react';
import DataTable from './DataTable';

const { useTable } = DataTable;

const SimpleDataTable = ({
    formConfig,
    columns,
    form,
    cardProps,
    fetchData,
    tableProps,
    rowKey,
    dataSource,
    after,
    updateQuery,
    initCollapsed
}) => {
    const [filters, setFilters] = useState({});
    const [sorters, setSorters] = useState({});
    const {
        pagination,
        setPagination,
        setData,
        data,
        setCollapsed,
        collapsed,
        DEFAULT_PAGINATION,
        fetchList,
        loading
    } = useTable(form, fetchData, filters, sorters, true, initCollapsed, updateQuery);
    const { current, pageSize } = pagination;
    const handleTable = (page, filtersArg, sorts) => {
        const extra = {};
        if (filters !== filtersArg) {
            extra.current = 1;
            setFilters(filtersArg);
        }
        if (sorters !== sorts) {
            extra.current = 1;
            setSorters(sorts);
        }
        setPagination({
            ...pagination,
            ...page,
            ...extra
        });
    };
    const handleSubmit = async () => {
        if (current === DEFAULT_PAGINATION.current && pageSize === DEFAULT_PAGINATION.pageSize) {
            fetchList();
        } else {
            setPagination({
                ...pagination,
                current: DEFAULT_PAGINATION.current,
                pageSize: DEFAULT_PAGINATION.pageSize
            });
        }
    };

    useEffect(() => {
        if (dataSource) {
            setData(dataSource);
        }
    }, [dataSource]);

    return (
        <Fragment>
            <DataTable
                data={data}
                pagination={pagination}
                handleSubmit={handleSubmit}
                handleTable={handleTable}
                form={form}
                cardProps={cardProps}
                columns={columns}
                formConfig={formConfig}
                collapsed={collapsed}
                setCollapsed={setCollapsed}
                loading={loading}
                tableProps={tableProps}
                setPagination={setPagination}
                rowKey={rowKey}
                filters={filters}
                sorters={sorters}
            />
            {after && after(fetchList)}
        </Fragment>
    );
};

export default SimpleDataTable;
